package com.algorithm.snowflake;

/**
 * 功能描述
 *
 * @author fujc-dev@qq.com
 * @date: 2023年08月24日 9:21
 */

import java.math.BigInteger;
import java.util.UUID;

public class UUIDToDecimalNumber {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            UUID uuid = UUID.randomUUID();
            // 指定数字长度为40位，不足长度补齐
            BigInteger decimalNumber = convertUuidToDecimalNumber(uuid, 40);
            System.out.println(decimalNumber);
        }
    }

    /**
     * @param uuid   UUID
     * @param length 数据长度
     * @return 格式化后的ID
     */
    public static BigInteger convertUuidToDecimalNumber(UUID uuid, int length) {
        byte[] byteArray = convertUuidToByteArray(uuid);
        // 使用正数的byte数组创建BigInteger
        BigInteger decimalNumber = new BigInteger(1, byteArray);

        // 获取生成的数字的字符串表示
        String decimalString = decimalNumber.toString();

        // 补齐指定长度
        int paddingLength = length - decimalString.length();
        //System.out.println("length:" + paddingLength);
        if (paddingLength <= 0) {
            return decimalNumber;
        }

        StringBuilder paddedDecimal = new StringBuilder(decimalString);
        for (int i = 0; i < paddingLength; i++) {
            paddedDecimal.append("0");
        }

        return new BigInteger(paddedDecimal.toString());
    }

    public static byte[] convertUuidToByteArray(UUID uuid) {
        long mostSignificantBits = uuid.getMostSignificantBits();
        long leastSignificantBits = uuid.getLeastSignificantBits();

        byte[] byteArray = new byte[16];
        for (int i = 0; i < 8; i++) {
            byteArray[i] = (byte) (mostSignificantBits >>> (8 * (7 - i)));
            byteArray[i + 8] = (byte) (leastSignificantBits >>> (8 * (7 - i)));
        }

        return byteArray;
    }
}





